﻿@using Enter.Admin.Dtoes
@using Enter.Admin.Utils
@using Enter.Admin.Models.DataTables
@{
    ViewData["Title"] = "模板";
    var columns = DataTablesColumnExt.ToList<ArchiveModel>();
}
@section Styles {
    <link href="~/plugins/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="~/plugins/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" rel="stylesheet" />

    <link href="~/plugins/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css" rel="stylesheet" />

    <link href="~/plugins/dropzone/dist/min/dropzone.min.css" rel="stylesheet" />
    <link href="~/plugins/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet" />
    <link href="~/plugins/jquery-transfer/icon_font/css/icon_font.css" rel="stylesheet" />
    <link href="~/plugins/jquery-transfer/css/jquery.transfer.css" rel="stylesheet" />
}
@section Scripts {
    <script src="~/plugins/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="~/plugins/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
    <script src="~/plugins/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js"></script>
    <script src="~/plugins/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
    <script src="~/plugins/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js"></script>

    <script src="~/plugins/dropzone/dist/min/dropzone.min.js"></script>
    <script src="~/plugins/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
    <script src="~/plugins/sweetalert/dist/sweetalert.min.js"></script>
    <script src="~/plugins/jquery-transfer/js/jquery.transfer.js?v=0.0.6"></script>
    <script src="~/plugins/parsleyjs/dist/parsley.min.js"></script>
    <script src="~/plugins/parsleyjs/dist/i18n/zh_cn.extra.js"></script>
    <script src="~/plugins/parsleyjs/dist/i18n/zh_cn.js"></script>
    <script>
        var searchObj = function () {
            return ""//{}
        }
        var all_columns = @Html.Raw(Jsons.Serialize(columns));
        var transfer = null
        var dataTable = null

        // 新增模板
        var editTemplate = function (tableId,name) {
            $("#TableId").val(tableId)
            $("#Name").val(name)
            $("#modal-dialog-template").modal()
        }
        var handleDataTableDefault = function () {
            if ($('#data-table-default').length !== 0) {
                dataTable = $('#data-table-default').DataTable({
                    "serverSide": true,
                    "ajax": {
                        type: "POST",
                        url: '@Url.Action("Index", "Template")',
                        contentType: "application/json; charset=utf-8",
                        async: true,
                        data: function (data) {
                            data.Data = searchObj()
                            data.columns = []
                            return JSON.stringify(data);
                        }
                    },
                    paging: false,
                    "searching": false,
                    dom: 'Btip',
                    buttons: [
                        {
                            text: '新增 <i class="fa fa-plus"></i>',
                            className:'btn btn-primary',
                            action: function (e, dt, node, config) {
                                editTemplate(0,"")
                            }
                        }
                    ],
                    columns: [{ title: "模板", data: "Name", orderable: false }, { title: "操作", data: "Id", orderable: false }],
                    "columnDefs": [
                        {
                            "targets": -1,
                            "width": "250px",
                            render: function (data, type, full, meta) {
                                return '<a class="btn btn-sm btn-info" href="javascript:;" onclick="show_modal(' + full.Id + ')">配置 <i class="fas fa-sliders-h"></i></a> '
                                    + '<a class="btn btn-sm btn-info" href="javascript:;" onclick="editTemplate(' + full.Id + ',\'' + full.Name + '\')">修改名称 <i class="fa fa-edit"></i></a> '
                                    + '<a class="btn btn-sm btn-info btn-delete" data-message="' + full.RoleName + '" data-id="' + full.Id + '">删除 <i class="fa fa-trash-alt"></i></a>';
                            }
                        }
                    ],
                    "language": datatable_language
                });
            }
        };

        var deleteRow = function (id, message) {
             // https://github.com/t4t5/sweetalert
            swal({
                title: '确定删除 "' + message+'" 吗?',
                text: '删除后不能恢复!',
                icon: 'warning',
                buttons: {
                    cancel: {
                        text: '取消',
                        value: null,
                        visible: true,
                        className: 'btn btn-default',
                        closeModal: true,
                    },
                    confirm: {
                        text: '删除',
                        value: true,
                        visible: true,
                        className: 'btn btn-warning',
                        closeModal: true
                    }
                }
            }).then(willDelete => {
                if (willDelete) {
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: "@Url.Action("Delete", "Template")" + "/" + id,// ,new {id = Model.Id }
                        data: $("#form-delete").serialize(),
                        success: function (result) {
                            if (result.Success) {
                                dataTable.ajax.reload();
                            } else {
                                show_alert('warning', result.Message)
                            }
                        },
                        error: function (e) {
                            show_alert('error', '网络异常.')
                        }
                    });
                }
            });
        };


        var transfer_export = function (data) {
            $("#transfer-export").empty()
            var default_selected = data.map(({ ColumnName }) => (ColumnName));
            var dataArray = []
            //var columns = all_columns.slice()
            for (let i = 0; i < all_columns.length; i++) {
                var item = all_columns[i]
                dataArray.push({
                    "data": item.data,
                    "title": item.title,
                    "selected": default_selected.includes(item.data)
                })
            }
            var settings1 = {
                "dataArray": dataArray,
                "itemName": "title",
                "valueName": "data",
                tabNameText: "未选择的项",
                rightTabNameText: "已选择的项",
                searchPlaceholderText: "搜索",
                //"callable": function (items) {
                //    console.dir(items)
                //}
            };
            transfer = $("#transfer-export").transfer(settings1);
            // var columns = transfer.getSelectedItems().map(({ data }) => (data));
        }

        var show_modal = function (id) {
            $("#SelectTableId").val(id)
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: "@Url.Action("Items", "Template")" + "?tableId=" + id,
                success: function (result) {
                    if (result.Success) {
                        transfer_export(result.Data)
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
            $('#modal-dialog-export').modal();
        }

        var edit = function () {
            if (!$('#form-add').parsley().validate()) return;
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "@Url.Action("Edit", "Template")",// ,new {id = Model.Id }
                data: $("#form-add").serialize(),
                success: function (result) {
                    if (result.Success) {
                        dataTable.ajax.reload();
                        $("#modal-dialog-template").modal('hide')
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
        }

        var saveItems = function () {
            var tableId = $("#SelectTableId").val()
            var columns = transfer.getSelectedItems().map(({ data }) => (data));
           
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                url: "@Url.Action("AddItems", "Template")",
                data: JSON.stringify({
                    TableId: tableId,
                    Columns: columns
                }),
                success: function (result) {
                    if (result.Success) {
                        $("#modal-dialog-export").modal('hide')
                    } else {
                        show_alert('warning', result.Message)
                    }
                },
                error: function (e) {
                    show_alert('error', '网络异常.')
                }
            });
        }

        $(document).ready(function () {
            handleDataTableDefault();
            //transfer_export()
            $("#data-table-default").on("click", ".btn-delete", function (e) {
                e.preventDefault();
                var id = $(this).attr("data-id");
                var message = $(this).attr("data-message");
                deleteRow(id, message)
            });
            $("#modal-dialog-template-button").click(function () {
                edit()
            })
            $("#modal-dialog-export-button").click(function () {
                saveItems()
            })
        });

    </script>
}

<!-- begin breadcrumb -->
<ol class="breadcrumb float-xl-right">
    <li class="breadcrumb-item"><a href="javascript:;">案件管理</a></li>
    <li class="breadcrumb-item active">模板管理</li>
</ol>
<!-- end breadcrumb -->
<!-- begin page-header -->
<h1 class="page-header">模板管理 <small>...</small></h1>
<!-- end page-header -->
<!-- begin panel -->
<div class="panel panel-inverse">
    <!-- begin panel-heading -->
    <div class="panel-heading">
        <h4 class="panel-title">模板列表</h4>
        <div class="panel-heading-btn" style="padding-left: 10px;">
            <a href="@Url.Action("Index", "Home")" class="btn btn-xs btn-primary">返回列表<i class="fas fa-backward"></i></a>
        </div>
    </div>
    <!-- begin panel-body -->
    <div class="panel-body">
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-export" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">选择项</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <input type="text" id="SelectTableId" name="SelectTableId" class="form-control" style="display:none" />
                        <div id="transfer-export" class="transfer-demo"></div>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-export-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- #modal-dialog -->
        <div class="modal fade" id="modal-dialog-template" data-backdrop="static">
            <div class="modal-dialog">
                <div class="modal-content" style="display: inline-block; width: auto;">
                    <div class="modal-header">
                        <h4 class="modal-title">新增模板</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    </div>
                    <div class="modal-body">
                        <form id="form-add" asp-action="Edit">
                            <input type="text" id="TableId" name="TableId" class="form-control" style="display:none" />
                            <input type="text" id="Name" name="Name" class="form-control" data-parsley-required="true" />
                        </form>
                    </div>
                    <div class="modal-footer">
                        <a href="javascript:;" class="btn btn-white" data-dismiss="modal">关闭</a>
                        <a href="javascript:;" id="modal-dialog-template-button" class="btn btn-primary">确定</a>
                    </div>
                </div>
            </div>
        </div>
        <form id="form-delete" style="display:none">@Html.AntiForgeryToken()</form>
        <table id="data-table-default" class="table table-striped table-bordered table-td-valign-middle display nowrap" style="width:100%">
        </table>
    </div>
    <!-- end panel-body   -->
</div>
<!-- end panel -->
